package com.lqk.java8.Lambda2;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * java8内置的四大核心函数式接口
 *      Comsumer<T> : 消费型接口
 *          void accept(T t);
 *      Supplier<T> : 供给型接口
 *          T get();
 *      Function<T,R> : 函数型接口
 *          R apply(T t);
 *      Predicate<T> : 断言型接口
 *          boolean test(T t);
 */
public class Lambda03 {
    //Comsumer<T> : 消费型接口
    @Test
    public void test1(){
        happy(1000, (money)-> System.out.println("大宝剑, 消费:"+money+"美元"));
    }
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }

    //Supplier<T> : 供给型接口
    @Test
    public void test2(){
        getNumList(10, ()->(int) (Math.random()*100))
                .stream()
                .forEach(System.out::println);

    }
    //需求: 产生指定个数的整数, 并放入集合中
    public List<Integer> getNumList(int count, Supplier<Integer> sup){
        List<Integer> list=new ArrayList<>();
        for (int i=0; i<count; i++){
            list.add(sup.get());
        }
        return list;
    }

    //Function<T,R> : 函数型接口
    @Test
    public void test3(){
        System.out.println(strHandle("尚硅谷yyds", (str)->str.substring(2,5)));
    }
    //需求: 用于处理字符串
    public String strHandle(String str, Function<String, String> fun){
        return fun.apply(str);
    }

    //Predicate<T> : 断言型接口
    //需求: 将满足条件的字符串放到集合中
    @Test
    public void test4(){
        List<String> list= Arrays.asList("Hello","lqk","Lambda","stream", "test");
        filterList(list, (str)->str.length()>3)
                                        .stream()
                                        .forEach(System.out::println);
    }
    public List<String> filterList(List<String> list, Predicate<String> pre){
        List<String> strList = list.stream()
                .filter(str -> pre.test(str))
                .collect(Collectors.toList());
        return strList;
    }
}
